package cn.abcsys.cloud.devops.pipeline.service.impl;

import java.sql.SQLException;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;

import cn.abcsys.cloud.devops.pipeline.common.GridBean;
import cn.abcsys.cloud.devops.pipeline.common.ImageObject;
import cn.abcsys.cloud.devops.pipeline.common.PagerModel;
import cn.abcsys.cloud.devops.pipeline.common.Status;
import cn.abcsys.cloud.devops.pipeline.common.SystemConfig;
import cn.abcsys.cloud.devops.pipeline.common.Validate;
import cn.abcsys.cloud.devops.pipeline.core.ImageCore;
import cn.abcsys.cloud.devops.pipeline.dao.ImageMapper;
import cn.abcsys.cloud.devops.pipeline.entity.Image;
import cn.abcsys.cloud.devops.pipeline.service.ImageService;
import cn.abcsys.cloud.devops.pipeline.util.Result;

/**
 * 镜像管理业务处理
 * @author mayunhao
 *
 */
@Component
public class ImageServiceImpl implements ImageService {
	private static final Logger LOGGER = Logger.getLogger(ImageServiceImpl.class);
	@Autowired
	private ImageMapper imageMapper;
	@Autowired
	private ImageCore imageCore;
	@Autowired
	private SystemConfig  systemConfig;
	@Override
	public Result insertImage(Image record) {
		Result result = null;
		try {
			record.setImageStatus((byte)Status.IMAGE.NORMAL.ordinal());
			int i = imageMapper.insertImage(record);
			if(i==1){
				result = new Result(true,"创建成功");
			}else{
				result = new Result(false,"创建失败");
			}
		} catch (SQLException e) {
			LOGGER.error("创建失败:"+e.getMessage());
			result = new Result(false, "创建失败："+e.getMessage());
		}
		return result;
	}

	@Override
	public Result deleteImage(Integer imageId) {
		Result result = null;
		try {
			int i = imageMapper.deleteImage(imageId);
			if(i==1){
				result = new Result(true,"删除成功");
			}else{
				result = new Result(false,"删除失败");
			}
		} catch (SQLException e) {
			LOGGER.error("删除失败:"+e.getMessage());
			result = new Result(false, "删除失败："+e.getMessage());
		}
		return result;
	}

	@Override
	public Result updateImage(Image record) {
		Result result = null;
		try {
			int i = imageMapper.updateImage(record);
			if(i==1){
				result = new Result(true,"更新失败");
			}else{
				result = new Result(false,"更新失败");
			}
		} catch (SQLException e) {
			LOGGER.error("更新失败:"+e.getMessage());
			result = new Result(false, "更新失败："+e.getMessage());
		}
		return result;
	}

	@Override
	public Result selectByPrimaryKey(Integer imageId) {
		Result result = null;
		try {
			Image image = imageMapper.selectByPrimaryKey(imageId);
			if(null!=image){
				result = new Result(true,JSONObject.toJSON(image),"success");
			}else{
				result = new Result(false,"未查到相关结果");
			}
		} catch (SQLException e) {
			LOGGER.error("查询镜像详情失败:"+e.getMessage());
			result = new Result(false, "查询失败："+e.getMessage());
		}
		return result;
	}

	@Override
	public List<Image> selectAllImageByEvn(Image image) {
		return null;
	}

	@Override
	public Result deleteBatchImage(List<Integer> list) {
		Result result = null;
		try {
			int i = imageMapper.deleteBatchImage(list);
			if(i==1){
				result = new Result(true,"删除成功");
			}else{
				result = new Result(false,"删除失败");
			}
		} catch (SQLException e) {
			LOGGER.error("删除失败:"+e.getMessage());
			result = new Result(false, "删除失败："+e.getMessage());
		}
		return result;
	}

	@Override
	public GridBean getImagePageList(PagerModel pagerModel) {
		int page = pagerModel.getPage();
		int rows = pagerModel.getRows();
		int totalpage = 0;
		Long totalNum = 0l;
		Page<Image> pageObject = new Page<Image>();
		try {
			Image image = new Image();
			PageHelper.startPage(page, rows);
			List<Image> images = imageMapper.selectAllImageByEvn(image);
			for(Image temp: images){
				pageObject.add(temp);
			}
			totalpage = ((Page<?>) images).getPages();
			totalNum = ((Page<?>) images).getTotal();
		} catch (SQLException e) {
			LOGGER.error("分页查询集群失败:"+e.getMessage());
		}
		GridBean gridBean = new GridBean(page, totalpage, totalNum.intValue(), pageObject);
		return gridBean;
	}
	/**
	 * 
	* @Title: uploadImage 
	* @Description: 镜像上传 
	* @param @param paramIn
	* @param @return    设定文件 
	* @return Result    返回类型 
	* @throws
	 */
	@Override
	public Result uploadImage(JSONObject paramIn){
		//输入参数校验
		Result result = Validate.imageInsertObjectValidate(paramIn);
		if(!result.isSuccess()){
			return result;
		}
		paramIn.put("hostname", systemConfig.getPipelineHostIp());
		paramIn.put("username", systemConfig.getPipelineHostUser());
		paramIn.put("password", systemConfig.getPipelineHostPwd());
    	String imageType = paramIn.getString("imageType");
    	int registryId = paramIn.getIntValue("registryId");
    	String imageDesc = paramIn.getString("imageDesc");
    	int envId = paramIn.getIntValue("envId");
    	int imageCreator = paramIn.getIntValue("userId");
    	
		Image image = new Image();
		image.setEnvId(envId);
		image.setUserId(imageCreator);
		image.setImageDesc(imageDesc);
		image.setImageStatus((byte)Status.IMAGE.NORMAL.ordinal());
		image.setImageScanStatus((byte)Status.JUDGE.NO.ordinal());
		image.setImageType(imageType);
		image.setRegistryId(registryId);
		result = imageCore.uploadImage(paramIn);
		if(!result.isSuccess()){
			return result;
		}
		
		imageCore.pushImage(paramIn);
		List<ImageObject> imageObjects = (List<ImageObject>)result.getData();
		for(ImageObject imageObject:imageObjects){
			image.setImageName(imageObject.getImageName());
			image.setImageTag(imageObject.getImageTag());
			image.setImageUuid(imageObject.getImageUuid());
			try {
				imageMapper.insertImage(image);
			} catch (SQLException e) {
				LOGGER.error(e);
			}
		}
		return new Result(true, "upload success");
	}
}
